import React, { useRef, useState} from 'react'
import axios from 'axios'
import { Link } from 'react-router-dom'

export default function Home() {
    const searchRef = useRef()
    const [items, setItems] = useState(localStorage.getItem('items')?JSON.parse(localStorage.getItem('items')):[])
    const [isLoading, setIsLoading] = useState(false)


    const searchUserList = function (e) {
        e.preventDefault()
        const q = searchRef.current.value.trim()
        setIsLoading(true)
        axios.get('https://api.github.com/search/users', {
            params: {
                q: q,
                sort: 'stars'
            }
        }).then((value) => {
            setItems(value.data.items)
            localStorage.setItem('items', JSON.stringify(value.data.items))
            localStorage.setItem('q', q)
            setIsLoading(false)
        })
    }


    return (
        <div>
            <form onSubmit={searchUserList}>
                <input type="text" defaultValue={localStorage.getItem('q')} ref={searchRef} />
                <button type='submit'>搜索</button>
            </form>
            {
                isLoading?<h3>正在加载中。。。</h3>:items.map((item) => {
                    return (
                        <p key={item.id}>
                            <Link to={"/details/"+item.login+'.html'}>{item.login}</Link>
                        </p>
                    )
                })
            }
        </div>
    )
}
